package com.nai365.nart.search.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nai365.nart.common.core.constant.SecurityConstants;
import com.nai365.nart.common.core.es.SpuEsModel;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.security.annotation.Inner;
import com.nai365.nart.search.service.MallSearchService;
import com.nai365.nart.search.vo.SearchParam;
import com.nai365.nart.search.vo.SearchResult;
import com.nai365.nart.search.vo.SearchSkuParam;
import com.nai365.nart.search.vo.SearchSkuResult;
import com.nai365.nart.seckill.api.feign.SeckillFeignService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: baogs
 * @createTime: 2021-03-12 18:07
 **/

@RestController
@Api(value = "搜索", tags = "搜索模块")
@AllArgsConstructor
public class SearchController {

    @Autowired
    private MallSearchService mallSearchService;
    private SeckillFeignService seckillfeignService;

    /**
     * 自动将页面提交过来的所有请求参数封装成我们指定的对象
     * @param param
     * @return
     */
    @GetMapping(value = "/list_search")
	@ApiOperation(value ="搜索" ,notes = "搜索")
    public R listPage(SearchParam param, Page page) {


        //1、根据传递来的页面的查询参数，去es中检索商品
        SearchResult result = mallSearchService.search(param);


        return R.ok(result);
    }
    /**
     * 自动将页面提交过来的所有请求参数封装成我们指定的对象
     * @param param
     * @return
     */
    @GetMapping(value = "/list_search_inner")
	@ApiOperation(value ="搜索一级市场产品" ,notes = "搜索")
	@Inner(value = false)
    public R listPageInner(SearchParam param, Page page) {


        //1、根据传递来的页面的查询参数，去es中检索商品
        SearchResult result = mallSearchService.search(param);

		List<SpuEsModel> product = result.getProduct();
		product.parallelStream().forEach(item ->handlerStatus(item) );

		return R.ok(result);
    }

	/**
	 * 处理藏品状态
	 **/
	private void handlerStatus(SpuEsModel byId) {
		int status = 0;
		R r = seckillfeignService.skuCount(byId.getId() + "", SecurityConstants.FROM_IN);
		if (r.getCode() == 0 && r.getData() != null) {
			Integer count = Integer.parseInt(r.getData().toString());
			if (count > 0) {
				status = 7;
			}
		}

		Integer sellPattern = byId.getSellPattern();
		LocalDateTime prioritySellBeginTime = byId.getPrioritySellBeginTime();
		LocalDateTime prioritySellEndTime = byId.getPrioritySellEndTime();
		LocalDateTime drawBeginTime = byId.getDrawBeginTime();
		LocalDateTime drawEndTime = byId.getDrawEndTime();
		LocalDateTime now = LocalDateTime.now();
		boolean before = now.isBefore(prioritySellBeginTime);
		if (before) {
			status = 1;
		} else if (now.isBefore(prioritySellEndTime) && now.isAfter(prioritySellBeginTime)) {
			status = 2;
		} else if (now.isBefore(drawBeginTime) && now.isAfter(prioritySellEndTime)) {
			status = 3;
		} else if (now.isBefore(drawEndTime) && now.isAfter(drawBeginTime)) {
			status = 4;
		} else if (now.isBefore(drawEndTime.plusMinutes(15)) && now.isAfter(drawEndTime)) {
			status = 5;
		} else if (now.isAfter(drawEndTime.plusMinutes(15))) {
			status = 6;
		}

		if (sellPattern == 1 && (status == 1 || status == 2 || status == 3 || status == 6 || status == 7)) {
			byId.setStatus(status);
		} else if (sellPattern == 3 && (status == 1 || status == 6 || status == 7)) {
			byId.setStatus(status);
		} else {
			byId.setStatus(status);
		}
	}
    /**
     * 自动将页面提交过来的所有请求参数封装成我们指定的对象
     * @param param
     * @return
     */
    @GetMapping(value = "/list_search_sku_inner")
	@ApiOperation(value ="搜索二级市场产品" ,notes = "搜索")
	@Inner(value = false)
    public R listPageSkuInner(SearchSkuParam param) {


        //1、根据传递来的页面的查询参数，去es中检索商品
        SearchSkuResult result = mallSearchService.searchSku(param);


        return R.ok(result);
    }


	/**
	 * 自动将页面提交过来的所有请求参数封装成我们指定的对象
	 * @param param
	 * @return
	 */
	@GetMapping(value = "/list_search_sku_stat_inner")
	@ApiOperation(value ="搜索二级市场产品统计结果" ,notes = "搜索")
	@Inner(value = false)
	public R listPageSkuStatInner(Long spuId ,Integer type) {
		type = type != null ? type : 2;
		SearchSkuParam searchSkuParam = new SearchSkuParam();
		searchSkuParam.setSpuId(spuId);
		searchSkuParam.setType(type);

		//1、根据传递来的页面的查询参数，去es中检索商品
		SearchSkuResult result = mallSearchService.searchSku(searchSkuParam);


		return R.ok(result);
	}
	@PostMapping(value = "/list_search_spus_stat_inner")
	@ApiOperation(value ="搜索二级市场产品平均价统计结果" ,notes = "搜索")
	@Inner(value = false)
	public R listPageSpusStatInner(@RequestBody List<Long> spuIds , Integer type) {
		type = type != null ? type : 2;
		SearchSkuParam searchSkuParam = new SearchSkuParam();
		searchSkuParam.setSpuIds(spuIds);
		searchSkuParam.setType(type);

		//1、根据传递来的页面的查询参数，去es中检索商品
		SearchSkuResult result = mallSearchService.searchSku(searchSkuParam);
		JSONObject spu = JSONUtil.parseObj(result.getStats());
		JSONArray spus = (JSONArray) spu.get("buckets");
		Map entries = new HashMap();
		spus.parallelStream().forEach(item -> {
			try {
				JSONObject info = JSONUtil.parseObj(item);
				Object key = info.get("key");
				JSONArray aggregations = (JSONArray) info.get("aggregations");
				JSONObject o = (JSONObject) aggregations.get(0);
				Object value = o.get("value");
				entries.put(key.toString(),value);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}

		});
		return R.ok(entries);
	}
	/**
	 * 自动将页面提交过来的所有请求参数封装成我们指定的对象
	 * @param param
	 * @return
	 */
	@GetMapping(value = "/list_search_sku_info_inner")
	@ApiOperation(value ="搜索二级市场产品统计结果" ,notes = "搜索")
	@Inner(value = false)
	public R listPageSkuInfoInner(Long skuId ,Integer type) {
		type = type != null ? type : 2;
		SearchSkuParam searchSkuParam = new SearchSkuParam();
		searchSkuParam.setSkuId(skuId);
		searchSkuParam.setType(type);

		//1、根据传递来的页面的查询参数，去es中检索商品
		SearchSkuResult result = mallSearchService.searchSku(searchSkuParam);


		return R.ok(result);
	}








}
